package com.nhjf.client;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.nhjf.client.request.OpenRequest;
import com.nhjf.client.response.OpenResponse;
import com.nhjf.common.util.HttpResponse;
import com.nhjf.common.util.HttpUtil;
import com.nhjf.common.util.LogFlow;
import com.nhjf.common.util.Md5Util;

public class OpenServiceClient {

	private String clientKey;
	private String secretKey;
	
	private Integer timeout = 15000;
	private String baseUrl = "http://127.0.0.1:7080/webMobile";

	public OpenServiceClient(String baseUrl, String clientKey, String secretKey) {
		if (baseUrl != null) {
			this.baseUrl = baseUrl;
		}
		this.clientKey = clientKey;
		this.secretKey = secretKey;
	}

	@SuppressWarnings("unchecked")
	public <T extends OpenResponse> T send(OpenRequest request) {

		StringBuilder pathBuilder = new StringBuilder(baseUrl);
		pathBuilder.append(request.getServiceUri());

		String msg = JSON.toJSONString(request);
		long ts = new Date().getTime();
		
		String sign = Md5Util.MD5(clientKey + secretKey + ts + msg);
		
		StringBuilder paramBuilder = new StringBuilder("param=");
		try {
			paramBuilder.append(URLEncoder.encode(JSON.toJSONString(request),
					"UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// 加签名处理
		paramBuilder.append("&clientKey=").append(clientKey).append("&sign=")
				.append(sign).append("&ts=").append(ts);

		LogFlow flow = new LogFlow("开始发送请求:" + paramBuilder.toString());
		HttpResponse response = HttpUtil.reqForPost(pathBuilder.toString(), paramBuilder.toString(), timeout);
		flow.record("请求结束:" + JSON.toJSONString(response));
		
		String result = response.getResult();
		flow.print();
		return (T) JSON.parseObject(result, request.getResponseClazz());
	}

	public Integer getTimeout() {
		return timeout;
	}

	public void setTimeout(Integer timeout) {
		this.timeout = timeout;
	}

}
